package src;

import javax.swing.*;
import java.awt.*;
import java.awt.Window;
import java.sql.*;

public class SalesmanAddDialog extends AddDialog {
    public SalesmanAddDialog(Window parent, Connection connection) {
        super(parent, "添加业务员信息", connection);
        
        // 自动生成业务员ID
        String nextSalesmanId = generateNextSalesmanId();
        JTextField salesmanIdField = new JTextField(nextSalesmanId);
        salesmanIdField.setEditable(false);
        addInputField("ID:", salesmanIdField);
        
        addInputField("姓名:", new JTextField());
        addInputField("电话:", new JTextField());

        confirmButton.addActionListener(e -> {
            try {
                String sql = "INSERT INTO salesman (salesman_id, name, phone) VALUES (?, ?, ?)";
                PreparedStatement pstmt = connection.prepareStatement(sql);
                pstmt.setString(1, salesmanIdField.getText());
                pstmt.setString(2, textFields.get("姓名:").getText());
                pstmt.setString(3, textFields.get("电话:").getText());
                
                pstmt.executeUpdate();
                JOptionPane.showMessageDialog(this, "业务员添加成功！");
                dispose();
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(this, "添加业务员失败: " + ex.getMessage());
            }
        });
    }

    private String generateNextSalesmanId() {
        try {
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT salesman_id FROM salesman ORDER BY salesman_id");
            
            if (!rs.next()) {
                return "S001";
            }
            
            java.util.Set<Integer> usedIds = new java.util.HashSet<>();
            do {
                String currentId = rs.getString("salesman_id");
                int num = Integer.parseInt(currentId.substring(1));
                usedIds.add(num);
            } while (rs.next());
            
            int nextNum = 1;
            while (usedIds.contains(nextNum)) {
                nextNum++;
            }
            
            return String.format("S%03d", nextNum);
            
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "生成业务员ID失败: " + e.getMessage());
            return "S001";
        }
    }
} 